package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

	@Autowired
	OrderSettingDao orderSettingDao;

	@Override
	@Transactional
	public void addOrderSettingList(List<OrderSetting> orderSettings) {


		for (OrderSetting ordersettion : orderSettings
				) {
			saveOrEdit(ordersettion);
		}


	}

	@Override
	public List<OrderSetting> getOrderSettingByMonth(String date){

		String startDate = date + "-01";
		String endDate = null;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		//把当月1号转换为日期类型
		try {
			Date dateParse = sdf.parse(startDate);

		//转换为Calender对象
		Calendar cal = Calendar.getInstance();
		cal.setTime(dateParse);
		//修改日期为下个月1号
		cal.add(Calendar.MONTH, 1);
		//修改为前一天,（下个月1号的前一天，是这个月的最后一天）
		cal.add(Calendar.DAY_OF_MONTH, -1);
		//转换为Date类型
		Date thisMonthLastDay = cal.getTime();
		endDate = sdf.format(thisMonthLastDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		List<OrderSetting> orderSettingList = orderSettingDao.findOrderSettingsByDate(startDate, endDate);
		return orderSettingList;
	}

	@Override
	public void add(OrderSetting orderSetting) {

		//根据预约设置的日期查询数据库中的预约设置对象
		OrderSetting orderSettingDb = orderSettingDao.findByDate(orderSetting.getOrderDate());
		if(orderSettingDb == null){
			//没有进行预约设置，直接添加
			orderSettingDao.add(orderSetting);
		}else{
			//已经进行预约设置，修改
			//获取已预约人数
			int reservations = orderSettingDb.getReservations();
			//获取可预约人数
			int number = orderSetting.getNumber();
			//已预约人数大于可预约人数，抛出异常
			if(reservations > number){
				throw  new RuntimeException("已预约人数大于可预约人数，批量导入失败!!!!");
			}
			//已预约人数小于等于可预约人数，直接修改
			else{
				orderSettingDao.edit(orderSetting);
			}
		}

	}

	@Transactional
	public void saveOrEdit(OrderSetting orderSetting) {

		OrderSetting orderSettingDb = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());

		if (orderSettingDb == null) {

			orderSettingDao.add(orderSetting);
			System.out.println("orderSetting添加成功");

		} else {

			if (orderSettingDb.getReservations() > orderSetting.getNumber()) {

				throw new RuntimeException("已预约人数大于可预约人数,不可设置");

			} else {
				orderSettingDao.edit(orderSetting);
			}


		}

	}
}
